package com.gao.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gao.entity.LoginUser;
import com.gao.entity.Permission;
import com.gao.entity.Role;
import com.gao.entity.User;
import com.gao.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author gao
 * @time 2022/11/06 10:54:32
 */
@Service
@Transactional
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户，附带角色和权限
        User user = userMapper.selectUserWithRoleAndPermission(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }

        Set<Role> roles = user.getRoles();
        Set<String> stringRoles = roles.stream().map(r -> "ROLE_" + r.getRname()).collect(Collectors.toSet());

        Set<Permission> permissions = user.getPermissions();
        Set<String> stringPermissions = permissions.stream().map(p -> p.getPname()).collect(Collectors.toSet());

        stringPermissions.addAll(stringRoles);

        // 返回用户
        return new LoginUser(user, stringPermissions);
    }
}
